package com.zbiti.anvil.basic.admin.gateway.sso.sso1;

import org.apache.commons.lang3.time.DateFormatUtils;

import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.Date;

/**
 * SSO认证工具包
 *
 * @author Fanyc
 * @date 2024/9/3 14:53
 */
public class AnvilSsoUtil {

    /**
     * 凭据数据部分格式：登录名@appId@customData@timestamp
     */
    public static final String REG_PRINCIPAL_DATA = "%s@%s@%s@%s";

    /**
     * 时间戳格式：yyyyMMddHHmmss
     */
    public static final String TIMESTAMP_FORMAT = "yyyyMMddHHmmss";

    public static String generateAutoLoginPrincipal(final String loginName, final String customData, final String appId, final String privateKey) throws InvalidKeySpecException, NoSuchAlgorithmException {
        // 如果自定义数据为空，默认为空字符串
        String _customData = (customData != null ? customData : "");
        // 签名加密方式：登录名@appId@customData@timestamp@sign
        String data = String.format(REG_PRINCIPAL_DATA, loginName, appId, _customData, DateFormatUtils.format(new Date(), TIMESTAMP_FORMAT));
        // 生成加密后的签名
        String sign = RSAUtil.privateEncrypt(data, privateKey);
        // 签名加密方式：登录名@appId@customData@timestamp@sign
        return String.format("%s@%s", data, sign);
    }
}
